<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/8/14
 * Time: 11:14
 */

namespace pay\modules\frontend\controllers;

use GatewayWorker\Lib\Gateway;
use pay\libs\Tools;
use Yii;
use yii\log\FileTarget;
use yii\web\Controller;

class WebSocketController extends Controller
{

    public function beforeAction($action)
    {
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        $allow_origin = array(
            'http://10.9.87.108:8080',
            'http://view.horsevision.cn',
            'http://10.9.87.99:8080',
        );
        // P($origin);
        if (in_array($origin, $allow_origin)) {
            header('Access-Control-Allow-Origin:' . $origin);
            header('Access-Control-Allow-Methods:POST,GET');
            header('Access-Control-Allow-Credentials:true');
        }

        return true;
    }


    /*** clinedId 绑定到订单号，方便后面订单通知
     * @return false|string
     */
    public function actionBindOrderNo(){

        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $client_id = isset($post['client_id'])?$post['client_id']:'';
            $payNo = isset($post['payNo'])?$post['payNo']:'';
            if  (empty($client_id) || empty($payNo)){
                return Tools::showRes(99,'绑定失败，参数有误');
            }
            Gateway::$registerAddress = '127.0.0.1:1236';
            Gateway::bindUid($client_id,$payNo);
            return Tools::showRes(0,'绑定成功');

        }
    }


    public function actionSendOrderStatus()
    {
        $post = Yii::$app->request->post();
        $payNo = isset($post['payNo'])?$post['payNo']:'';
        $data = array(
            'type' => 'payStatus',
            'data' => array(
                'payNo' => $payNo,
                'payStatus'  => 3,

            )
        );
        Gateway::sendToUid($payNo,json_encode($data));
        return Tools::showRes(0,'success');

    }

    public function actionTest()
    {
        $data = array(
            'type' => 'payStatus',
            'data' => array(
                'payNo' => '12341234123412',
                'payStatus'  => 3,

            )
        );
        Gateway::sendToGroup('123412341212341',json_encode($data));
    }
    

    protected function recordLogin($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/websocket/log_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }





}